/*
 解析器。地磅的数据有多种格式，常用的有TF0格式，以后就什么格式直接写解析器。
 解析成功返回重量字符串，解析错误返回false
*/
exports.parser = {
  decode : function(buf) {
    if(!Buffer.isBuffer(buf)) return false;
    
    if( (buf.length===12) && (buf[0]===0x02) && (buf[11]===0x03) ) {
      return this.tf0(buf);
    } else if( (buf.length===8) && (buf[0]===0x3D) ) {
        return this.ds2o(buf);
    } else {
      return false;
    }
  },
  
  tf0 : function(buf){
    

    // TODO校验
    
    //02 2b 30 30 30 30 30 30 30 31 42 03
    //0 0 0 0 0 8 | 2
    //0 0 0 0 8 0 | 0
    //9 9 9 9 8 0 | 0999.980

    let poi = buf[8]-0x30;

    let weight;
    if(poi == 0) {// v0.3 针对部分小吨位显示为KG的情况，如成元化工
      weight = Buffer.concat([Buffer.from('0'), buf.slice(2,5) , Buffer.from('.'),  buf.slice(5,7)] );
    } else {
      weight = Buffer.concat( [buf.slice(2,8-poi) , Buffer.from('.'), buf.slice(8-poi , 8)] );
    }

    weight = weight.toString().replace(/^0{1,3}/,''); // 去前导0
    if(buf[2]===0x2D) weight = '-'+weight; // 处理负号
    return weight;
  },
  
  ds2o : function(buf) {
    let weight;
    weight = Buffer.concat( [buf.slice(2,4) , Buffer.from('.') , buf.slice(4)] ); 
    weight = weight.toString().split("").reverse().join("").replace(/^0{1,3}/,''); // 去前导0;
    return weight;
  }
};